<?php

namespace App\Http\Controllers\App;

use App\Http\Controllers\Controller;
use App\Http\Requests\App\UploadWorkAttachmentRequest;
use App\Http\Requests\App\UserWorkStoreRequest;
use App\Http\Resources\App\WorkDetailResource;

use App\Models\Course;
use App\Models\UserWork;
use App\Models\Work;
use Illuminate\Http\Request;

class WorkController extends Controller
{
    public function index(Request $request, Course $course)
    {
        return WorkDetailResource::collection($course->works->load(['users' => function ($query) use ($request) {
            return $query->where('user_id', $request->user()->id)->withPivot(['review','result']);
        }]));
    }

    public function attach(UserWorkStoreRequest $request, Work $work)
    {
        if (UserWork::where('user_id', $request->user()->id)->where('work_id', $work->id)->exists()) {
            abort('422', '已提交过答案');
        }
        $result = $request->result;
        $review = [];
        if ($work->type == 1) {
            $isEqual = $request->result == $work->data['correct_selection'];
            if ($isEqual) {
                //相等
                $review['mark'] = 100;
            } else {
                $review['mark'] = 0;
            }
        } elseif ($work->type == 2) {
            $isEqual = collect($request->result)->sort()->values()->toArray() === collect($work->data['correct_selections'])->sort()->values()->toArray();
            $result = json_encode($request->result);
            if ($isEqual) {
                //相等
                $review['mark'] = 100;
            } else {
                $review['mark'] = 0;
            }
        }

        $work->users()->attach($request->user()->id, ['result' => $result, 'review' => $review]);
    }

    public function upload(UploadWorkAttachmentRequest $request)
    {

        $path = $request->attachment->store('public/attachment/work');
        $result = basename($path);
        return $result;

    }
}
